<?php


namespace app\api\controller;


use app\api\model\Collage\CollageModel;
use app\api\model\Goods\GoodsModel;
use app\api\model\Order\OrderGoodsModel;
use app\api\model\Order\OrderModel;
use app\api\model\School\SchoolWalletModel;
use app\api\model\User\MerchantWalletModel;
use app\api\model\User\UserApplyPartnerModel;
use app\api\model\User\UserModel;
use app\api\model\User\UserVipCodeModel;
use app\api\model\User\UserWalletModel;
use app\Utils\StrUtil;
use app\Utils\Util;
use Exception;
use think\facade\Db;
use think\facade\Log;

class AliNotify extends BaseController
{

    /**
     * 支付宝支付回调
     */
    public function index()
    {
        $trade_status = $_POST['trade_status'];
        if ($trade_status == 'TRADE_SUCCESS') {
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];
            //支付宝交易号
            $trade_no = $_POST['trade_no'];
            $buyer_pay_amount = $_POST['total_amount'];
            if (!empty($out_trade_no)) {
                $result = $this->payLogic($out_trade_no, $trade_no, $buyer_pay_amount);
                if ($result) {
                    echo "success";
                }
            }
        } else {
            echo "fail";
        }
    }

    /**
     * 合伙人回调
     */
    public function partner()
    {
        $trade_status = $_POST['trade_status'];
        if ($trade_status == 'TRADE_SUCCESS') {
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];
            //支付宝交易号
            $trade_no = $_POST['trade_no'];
            $buyer_pay_amount = $_POST['total_amount'];
            if (!empty($out_trade_no)) {
                $result = $this->payPartnerLogic($out_trade_no, $trade_no, $buyer_pay_amount);
                if ($result) {
                    echo "success";
                }
            }
        } else {
            echo "fail";
        }
    }

    /**
     * 支付处理函数
     * @param $out_trade_no
     * @param $trade_no
     * @param $buyer_pay_amount
     * @return bool
     * @throws
     */
    public static function payLogic($out_trade_no, $trade_no, $buyer_pay_amount)
    {
        $order = OrderModel::getOrderWhere([['out_trade_no', '=', $out_trade_no]]);
        if (!$order) {
            Log::record('支付宝回调错误' . $out_trade_no . '单号不存在');
            return false;
        }
        if ($order['status'] != 0) {
            Log::record('订单已支付');
            return true;
        }
        Db::startTrans();
        try {
            if (empty($order['status'])) {
                $goods = OrderGoodsModel::getOrderGoodsListWhereMore([['order_id', '=', $order['id']]]);
                if ($order['type'] == 1) {
                    #购买商品
                    //执行增加销量减库存操作
                    foreach ($goods as $item) {
                        $flag = GoodsModel::goodsInOut($item['goods_id'], $item['number']);
                        if (!$flag) {
                            Db::rollback();
                            return false;
                        }
                    }
                    if (!empty($order['is_group'])) {
                        if (!empty($order['temp_collage_id'])) {
                            //检查团是否已满
                            $collage = CollageModel::getCollageWhere(['id' => $order['temp_collage_id']]);
                            if (!empty($collage)) {
                                if (!empty($collage['status'])) {
                                    //团满开新团
                                    $collage_sn = StrUtil::i()->getOrderSn(2);
                                    $time = date("Y-m-d H:i:s", time());
                                    $end_time = date('Y-m-d H:i:s', strtotime($time) + 86400);
                                    $goodsInfo = GoodsModel::getGoodsWhere(['id' => $goods[0]['goods_id']]);
                                    $collage_data = [
                                        'collage_sn' => $collage_sn,
                                        'uid' => $order['uid'],
                                        'goods_id' => $goodsInfo['id'],
                                        'collage_count' => $goodsInfo['group_num'],
                                        'now_count' => 1,
                                        'up_time' => $time,
                                        'add_time' => $time,
                                        'mer_id' => $goodsInfo['mer_id'],
                                        'start_time' => $time,
                                        'end_time' => $end_time,
                                        'goods_info' => json_encode($goodsInfo),
                                    ];

                                    if (1 >= $goodsInfo['group_num']) {
                                        $collage_data['status'] = 1;
                                    } else {
                                        $collage_data['status'] = 0;
                                    }
                                    $collage_id = CollageModel::addCollage($collage_data);
                                    if (!empty($collage_id)) {
                                        $order_save = [
                                            'collage_id' => $collage_id
                                        ];
                                        OrderModel::updateOrderWhere(['id' => $order['id']], $order_save);
                                    } else {
                                        Log::record('拼团失败' . $out_trade_no . '创建拼团失败');
                                        throw new Exception();
                                    }
                                } else {
                                    //加入团
                                    $now_count = $collage['now_count'] + 1;
                                    $collage_save = [
                                        'now_count' => $now_count,
                                        'up_time' => date("Y-m-d H:i:s", time()),
                                    ];
                                    if ($now_count >= $collage['collage_count']) {
                                        $collage_save['status'] = 1;
                                    }
                                    CollageModel::updateCollageData(['id' => $collage['id']], $collage_save);
                                    $order_save = [
                                        'collage_id' => $order['temp_collage_id']
                                    ];
                                    OrderModel::updateOrderWhere(['id' => $order['id']], $order_save);
                                }
                            } else {
                                Log::record('拼团失败' . $out_trade_no . '团不存在');
                                throw new Exception();
                            }
                        } else {
                            //新增团
                            $collage_sn = StrUtil::i()->getOrderSn(2);
                            $time = date("Y-m-d H:i:s", time());
                            $end_time = date('Y-m-d H:i:s', strtotime($time) + 86400);
                            $goodsInfo = GoodsModel::getGoodsWhere(['id' => $goods[0]['goods_id']]);
                            $collage_data = [
                                'collage_sn' => $collage_sn,
                                'uid' => $order['uid'],
                                'goods_id' => $goodsInfo['id'],
                                'collage_count' => $goodsInfo['group_num'],
                                'now_count' => 1,
                                'up_time' => $time,
                                'add_time' => $time,
                                'mer_id' => $goodsInfo['mer_id'],
                                'start_time' => $time,
                                'end_time' => $end_time,
                                'goods_info' => json_encode($goodsInfo),
                            ];

                            if (1 >= $goodsInfo['group_num']) {
                                $collage_data['status'] = 1;
                            } else {
                                $collage_data['status'] = 0;
                            }
                            $collage_id = CollageModel::addCollage($collage_data);
                            if (!empty($collage_id)) {
                                $order_save = [
                                    'collage_id' => $collage_id
                                ];
                                OrderModel::updateOrderWhere(['id' => $order['id']], $order_save);
                            } else {
                                Log::record('拼团失败' . $out_trade_no . '创建拼团失败');
                                throw new Exception();
                            }
                        }
                    }
                } elseif ($order['type'] == 2) {
                    $goodsInfo = json_decode($goods[0]['goods_info'], true);
                    #购买会员
                    $user = UserModel::getUserWhere(['id' => $order['uid']], 'id,level_id,is_level_type,end_time,parent_uid,parent_reward');

                    //------开始发放佣金--------
                    if (!empty($order)) {
                        $order_goods = OrderGoodsModel::getOrderGoodsListWhereMore(['order_id' => $order['id']]);
                        if (!empty($order_goods)) {
                            foreach ($order_goods as $order_good) {
                                if ($order_good['is_sales'] == 1 || $order_good['is_sales'] == 2) {
                                    if (!empty($order_good['agnet_uid1']) && $order_good['agent_amount1'] > 0 && $order_good['agent_status1'] == 0) {
                                        UserWalletModel::walletIn($order_good['agnet_uid1'], $order_good['agent_amount1'], StrUtil::BILL_USE_TYPE['VIP_COMMISSION'], "购买会员佣金", $order_good['id']);
                                        OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status1' => 1]);
                                        Db::name('user_wallet')->where('uid', $order_good['agnet_uid1'])->inc('reward', $order_good['agent_amount1'])->update();
                                    }
                                    if (!empty($order_good['agnet_uid2']) && $order_good['agent_amount2'] > 0 && $order_good['agent_status2'] == 0) {
                                        UserWalletModel::walletIn($order_good['agnet_uid2'], $order_good['agent_amount2'], StrUtil::BILL_USE_TYPE['VIP_COMMISSION'], "购买会员佣金", $order_good['id']);
                                        OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status2' => 1]);
                                        Db::name('user_wallet')->where('uid', $order_good['agnet_uid2'])->inc('reward', $order_good['agent_amount2'])->update();
                                    }
                                    if (!empty($order_good['agnet_uid3']) && $order_good['agent_amount3'] > 0 && $order_good['agent_status3'] == 0) {
                                        UserWalletModel::walletIn($order_good['agnet_uid3'], $order_good['agent_amount3'], StrUtil::BILL_USE_TYPE['VIP_COMMISSION'], "购买会员佣金", $order_good['id']);
                                        OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status3' => 1]);
                                        Db::name('user_wallet')->where('uid', $order_good['agnet_uid3'])->inc('reward', $order_good['agent_amount3'])->update();
                                    }
                                }
                            }
                        }
                    }
                    //------结束发放佣金--------

                    if ($goodsInfo['type'] == 1) {
                        //永久
                        $data_user = [
                            'level_id' => $goodsInfo['id'],
                            'is_level_type' => 1
                        ];
                    } else {
                        if ($user['end_time']) {
                            if (strtotime($user['end_time']) > time()) {
                                $time = strtotime($user['end_time']) + ((int)$goodsInfo['day'] * 3600 * 24);
                            } else {
                                $time = time() + (((int)$goodsInfo['day'] * 3600 * 24));
                            }
                        } else {
                            $time = time() + (((int)$goodsInfo['day'] * 3600 * 24));
                        }
                        if (!empty($user['level_id']) && $user['level_id'] < $goodsInfo['id']) {
                            $data_user = [
                                'level_id' => $user['level_id'],
                                'is_level_type' => 0,
                                'end_time' => date('Y-m-d H:i:s', $time)
                            ];
                        } else {
                            $data_user = [
                                'level_id' => $goodsInfo['id'],
                                'is_level_type' => 0,
                                'end_time' => date('Y-m-d H:i:s', $time)
                            ];
                        }
                    }
                    $res_user = UserModel::updateUserWhere(['id' => $user['id']], $data_user);
                    if (false === $res_user) {
                        Log::record('支付宝回调错误' . $out_trade_no . '修改会员状态错误');
                        throw new Exception();
                    }

                } else if ($order['type'] == 3) {
                    $goods = $goods[0];
                    #购买课程
                    #增加课程销量
                    $result = Db::name('course')->where('id', $goods['goods_id'])->inc('sales', $order['pay_num'])->update();

                    if ($result === false) {
                        Log::record('支付宝回调错误' . $out_trade_no . '增加课程销量失败');
                        throw new Exception();
                    }
                    if ($goods['mer_id']) {
                        $goods['ratio'] = $goods['ratio'] > 1 ? 1 : $goods['ratio'];
                        #增加学校钱包余额
                        $result = SchoolWalletModel::walletIn($goods['mer_id'], round($goods['total_price'] * (1 - $goods['ratio']), 2), StrUtil::MER_BILL_USE_TYPE['SELL_COURSE'], '售卖课程');
                        if (false === $result) {
                            Log::record('支付宝回调错误' . $out_trade_no . '增加学校钱包余额失败');
                            throw new Exception();
                        }
                    }
                    if ($order['is_group']) {
                        $course = Db::name('course')->where('id', $goods['goods_id'])->find();
                        self::course_collage($order, $course);
                    }

                    //------开始发放佣金--------
                    if (!empty($order)) {
                        $order_goods = OrderGoodsModel::getOrderGoodsListWhereMore(['order_id' => $order['id']]);
                        if (!empty($order_goods)) {
                            foreach ($order_goods as $order_good) {
                                if ($order_good['is_sales'] == 1 || $order_good['is_sales'] == 2) {
                                    if (!empty($order_good['agnet_uid1']) && $order_good['agent_amount1'] > 0 && $order_good['agent_status1'] == 0) {
                                        UserWalletModel::walletIn($order_good['agnet_uid1'], $order_good['agent_amount1'], StrUtil::BILL_USE_TYPE['COURSE_COMMISSION'], "课程佣金", $order_good['id']);
                                        OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status1' => 1]);
                                        Db::name('user_wallet')->where('uid', $order_good['agnet_uid1'])->inc('reward', $order_good['agent_amount1'])->update();
                                    }
                                    if (!empty($order_good['agnet_uid2']) && $order_good['agent_amount2'] > 0 && $order_good['agent_status2'] == 0) {
                                        UserWalletModel::walletIn($order_good['agnet_uid2'], $order_good['agent_amount2'], StrUtil::BILL_USE_TYPE['COURSE_COMMISSION'], "课程佣金", $order_good['id']);
                                        OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status2' => 1]);
                                        Db::name('user_wallet')->where('uid', $order_good['agnet_uid2'])->inc('reward', $order_good['agent_amount2'])->update();
                                    }
                                    if (!empty($order_good['agnet_uid3']) && $order_good['agent_amount3'] > 0 && $order_good['agent_status3'] == 0) {
                                        UserWalletModel::walletIn($order_good['agnet_uid3'], $order_good['agent_amount3'], StrUtil::BILL_USE_TYPE['COURSE_COMMISSION'], "课程佣金", $order_good['id']);
                                        OrderGoodsModel::updateOrderGoodsWhere(['id' => $order_good['id']], ['agent_status3' => 1]);
                                        Db::name('user_wallet')->where('uid', $order_good['agnet_uid3'])->inc('reward', $order_good['agent_amount3'])->update();
                                    }
                                }
                            }
                        }
                    }
                    //------结束发放佣金--------

                }
                $save = [
                    'trade_no' => $trade_no,
                    'price' => $buyer_pay_amount,
                    'up_time' => date('Y-m-d H:i:s', time())
                ];
                if ($order['type'] == 3 || $order['type'] == 2) {
                    $save['status'] = 3;
                }
                if ($order['type'] == 1) {
                    $save['status'] = 1;
                }
                $flag = OrderModel::updateOrderWhere(['id' => $order['id']], $save);
                if (!$flag) {
                    Log::record('支付宝回调错误' . $out_trade_no . '修改订单状态失败');
                    throw new Exception();
                }
                $order_goods = OrderGoodsModel::getOrderGoodsListWhereMore([['order_id', '=', $order['id']]]);
                foreach ($order_goods as $item) {
                    $goods_save = [
                        'up_time' => date("Y-m-d H:i:s", time())
                    ];
                    if ($order['type'] == 3 || $order['type'] == 2) {
                        $goods_save['status'] = 3;
                    }
                    if ($order['type'] == 1) {
                        $goods_save['status'] = 1;
                    }
                    OrderGoodsModel::updateOrderGoodsWhere([['id', '=', $item['id']]], $goods_save);
                }
            }
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return false;

        }

    }

    /**
     * @param $order
     * @param $course
     * 记录拼团信息
     */
    protected function course_collage($order, $course)
    {

        $data = [
            'collage_sn' => $order['order_sn'],
            'course_id' => $course['id'],
            'user_id' => $order['uid'],
            'up_time' => date('Y-m-d H:i:s'),
            'add_time' => date('Y-m-d H:i:s'),
            'mer_id' => $order['mer_id'],
            'start_time' => $course['start_time'],
            'end_time' => $course['end_time'],
            'course_info' => $course
        ];
        Db::name('course_collage')->insert($data);
        return true;
    }

    /**
     * 合伙人支付处理函数
     * @param $out_trade_no
     * @param $trade_no
     * @param $buyer_pay_amount
     * @return bool
     */
    public static function payPartnerLogic($out_trade_no, $trade_no, $buyer_pay_amount)
    {
        $order = UserApplyPartnerModel::getUserApplyPartnerWhere([['out_trade_no', '=', $out_trade_no]]);
        if (!$order) {
            Log::record('支付宝合伙人回调错误' . $out_trade_no . '单号不存在');
            return false;
        }
        if ($order['status'] != 0) {
            Log::record('订单已支付');
            return true;
        }
        Db::startTrans();
        try {
            if (empty($order['status'])) {
                $data_user = [
                    'is_partner' => 1,
                    'up_time' => date('Y-m-d H:i:s', time())
                ];
                $res_user = UserModel::updateUserWhere(['id' => $order['uid']], $data_user);
                if (false === $res_user) {
                    Log::record('支付宝回调错误' . $out_trade_no . '修改会员合伙人状态错误');
                    throw new Exception();
                }
                $save = [
                    'trade_no' => $trade_no,
                    'status' => 1,
                    'up_time' => date('Y-m-d H:i:s', time())
                ];
                $flag = UserApplyPartnerModel::updateUserApplyPartnerWhere(['id' => $order['id']], $save);
                if (!$flag) {
                    Log::record('支付宝回调错误' . $out_trade_no . '修改订单状态失败');
                    throw new Exception();
                }
                //送激活码 10个激活码
                $list = UserVipCodeModel::getUserVipCodeListWhere(1, 10, [['uid', '=', ''], ['status', '=', 0]]);
                foreach ($list as $item) {
                    $code_save = [
                        'uid' => $order['uid'],
                        'up_time' => date("Y-m-d H:i:s", time())
                    ];
                    UserVipCodeModel::updateUserVipCodeWhere([['id', '=', $item['id']]], $code_save);
                }
            }
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return false;

        }
    }

}